const { Sequelize } = require('sequelize')
// const config = require('./dbConfig')
import logger from './logger'
import config from './config/config'

/**
 * 数据库连接池
 * @type {Object}
 */
const connections = {
  mysql: new Sequelize(config.database.mysql),
  // sqlite: new Sequelize(dbConfig.sqlite)
}

/**
 * 执行原始SQL查询
 * @param {string} sql - SQL语句
 * @param {object} options - 查询选项
 * @param {string} dbType - 数据库类型
 * @returns {Promise} 查询结果
 */
export async function executor(sql, options = {}, dbType = 'mysql') {
  const connection = connections[dbType]
  if (!connection) {
    throw new Error(`不支持的数据库类型: ${dbType}`)
  }

  try {
    const [results] = await connection.query(sql, options)
    logger.info('db.js', `executor-SQL: \n ${sql}`)
    logger.info('db.js', `executor-OPTIONS: \n ${JSON.stringify(options.replacements)}`)
    logger.info('db.js', `executor-SUCCESS: \n ${JSON.stringify(results)}`)
    // return {
    //   success: true,
    //   data: results
    // }
    return results
  } catch (error) {
    logger.error('db.js', `executor-SQL: ${sql}`)
    logger.error('db.js', `executor-OPTIONS: ${JSON.stringify(options.replacements)}`)
    logger.error('db.js', `executor-ERROR: ${JSON.stringify(error.message)}`)
    throw error
  }
}

/**
 * 关闭指定数据库的连接池
 * @param {string} dbType - 数据库类型
 */
export async function closeConnections(dbType) {
  if (dbType) {
    const connection = connections[dbType]
    if (connection) {
      await connection.close()
    }
  } else {
    // 关闭所有数据库连接
    for (const type in connections) {
      await connections[type].close()
    }
  }
}
